<?php

class MapRowIterator implements Iterator
{

   private $_sheet;
   public $header=null;
   private $_position = 2;

   public function __construct($sheet) {
      echo 'function __construct($sheet)';
      $this->_sheet=$sheet;
      //並取出第一個ROW

   }
   public function __destruct() {
      unset($this->_sheet);
      unset($this->header);
   }

   public function getHeader()
   {
      return $this->header;
   }

   public  function prefetchHeader()
   {
      
      $roit=$this->_sheet->getRowIterator();
      $row=$roit->current();
       
      $cellIterator = $row->getCellIterator();
      $cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
       
      $result=array();
      foreach ($cellIterator as $cell) {
         if (!is_null($cell)) {
            
            $v=$cell->getCalculatedValue();
            $result[]=$v;
         }else
            $result[]="";
      }
      return    $result;
   }

   public function rewind() {
      $this->_position = 2;
   }

   public function current() {
      if($this->header==null)
          $this->header=$this->prefetchHeader();
      
      //取出row.. 搭配
      // return $this->_subject->getSheet($this->_position);
      $row= new PHPExcel_Worksheet_Row($this->_sheet, $this->_position);

      $cellIterator = $row->getCellIterator();
      $cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set

      $idx=0;

      $result=array();
      foreach ($cellIterator as $cell) {
         if (!is_null($cell)) {
            $v=$cell->getCalculatedValue();

            $result[$this->header[$idx]] =$v; 
         }
         $idx++;
      }
      return  $result;

   }
   public function valid() {
   
      return $this->_position <= $this->_sheet->getHighestRow();
   }

   public function key() {
      return $this->_position;
   }
   public function next() {
      ++$this->_position;
   }
   public function prev() {
      if ($this->_position > 1)
         --$this->_position;
   }

   public function seek($row = 0) {
      $this->_position = $row+1;
   }
   public function getDataCount()
   {
      return $this->_sheet->getHighestRow()-1;
   }


}


?>